﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Web;

namespace DAL
{
    public class DbContextFactory
    {
        public static SysEntities DbContext
        {
            get
            {
                if(HttpContext.Current.Items["DBCONTEXT"]==null)
                {
                    HttpContext.Current.Items["DBCONTEXT"] = new SysEntities();
                }
                return (SysEntities) HttpContext.Current.Items["DBCONTEXT"];
            }
        }
    }

    public class SysEntities : DbContext
    {
        public SysEntities(): base("SysEntities")
        {
            // Database.CreateIfNotExists();
        }
        public DbSet<SysDepartment> SysDepartment 
        { get; set; }

        public DbSet<SysException> SysException
        { get; set; }

        public DbSet<SysField> SysField
        { get; set; }


        public DbSet<SysLog> SysLog
        { get; set; }


        public DbSet<SysMenu> SysMenu
        { get; set; }


        public DbSet<SysPerson> SysPerson
        { get; set; }

        public DbSet<SysRole> SysRole
        { get; set; }


        public DbSet<MyView> MyView
        { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<SysPerson>().HasOptional<SysDepartment>(u => u.SysDepartment);
            modelBuilder.Entity<SysPerson>().HasMany<SysRole>(u => u.SysRole).WithMany(u => u.SysPerson).Map(u => u.ToTable("SysRoleSysPerson").MapLeftKey("SysPersonId").MapRightKey("SysRoleId"));
            modelBuilder.Entity<SysRole>().HasMany<SysMenu>(u => u.SysMenu).WithMany(u => u.SysRole).Map(u => u.ToTable("SysMenuSysRole").MapLeftKey("SysRoleId").MapRightKey("SysMenuId"));
            base.OnModelCreating(modelBuilder);

        }


    }
}
